<template>
  <view class="container" :style="'top:'+top+'px'">
    <view class="message-header">
      <view class="read-all">
        <image style="margin-right: 10rpx;width: 15px;height: 15px" @click="back" :src="IMAGE_CONFIG.fanHui"></image>
        <text class="all" @click="markAllRead">
          全部已读
        </text>
      </view>
      <view class="title">消息</view>
    </view>
    <u-tabs @change="changeTab" :list="tabList" :current="currentTab" lineColor="#8F4C38" lineWidth="70px"></u-tabs>

    <view
        class="content-container"
        @touchstart="onTouchStart"
        @touchmove="onTouchMove"
        @touchend="onTouchEnd"
    >
      <view
          class="tab-content"
          :style="{ transform: `translateX(${(dragOffset - currentTab * 100)}%)`, transition: dragTransition }"
      >
        <view class="tab-pane" v-for="(tab, index) in tabList" :key="index">
          <!-- 每个 tab 的内容 -->
          <view class="message-item" v-for="(msg, idx) in messageList" :key="idx" @click="record(msg)">
            <view class="msg-header">
              <view class="msg-title">{{ msg.title }}</view>
              <view class="msg-time">{{ msg.sendTime?msg.sendTime.substr(0, 10) : '' }}</view>
              <view class="message-tips" v-if="!msg.isRead"></view>
<!--              <view class="toggle-btn" @click.stop="toggleExpand(idx)" v-if="msg.content && msg.content.length > 50">-->
<!--                {{ msg.isExpand ? '▲' : '▼' }}-->
<!--              </view>-->
              <img class="chapter-arrow-img" @click.stop="toggleExpand(idx)" v-if="msg.content && msg.content.length > 50" :class="{ open:  msg.isExpand }" src="https://fengqinghui.oss-cn-hangzhou.aliyuncs.com/monkey/monkey/zhanKaiMe.png" />
            </view>
            <view class="msg-content-wrapper">
              <view class="msg-content" :class="{ 'slide-down': msg.isExpand }">
                <view class="msg-text">{{ msg.content }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <u-popup :show="popupShow" mode="center" @close="close" :round="20">
      <view class="bind-child-popup">
        <view class="popup-title">{{ binding.title || '绑定请求' }}</view>
        <view class="popup-content">
          <view>申请人账号：{{ binding.applicantUserName }}</view>
          <view>申请时间：{{ binding.applyTime }}</view>
          <view>状态：{{ binding.statusStr }}</view>
        </view>
        <view class="popup-actions">
          <button class="btn-cancel" @click="confirmBind(false)">拒绝绑定</button>
          <button class="btn-confirm" @click="confirmBind(true)">确认绑定</button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import {getMaterialsPageList, postMessagesRead} from "../../api/new";
import {IMAGE_CONFIG} from '@/utils/imageConfig'
import {bindFamilyAuditApply} from "../../api/binding";

export default {
  data() {
    return {
      popupShow:false,
      IMAGE_CONFIG: IMAGE_CONFIG.message,
      tabList: [],
      currentTab: 100,
      startX: 0,
      dragOffset: 0,
      dragTransition: 'transform 0.3s ease',
      threshold: 50, // 滑动阈值（像素）
      messageList: [],
      list:[{},{},{},{},{}],
      top:0,
      conditions:[
        {
          id: undefined,
          messageType: undefined,
          page: 1,
          limit: 10,
        },
        {
          id: undefined,
          messageType: undefined,
          page: 1,
          limit: 10,
        },
        {
          id: undefined,
          messageType: undefined,
          page: 1,
          limit: 10,
        },
        {
          id: undefined,
          messageType: undefined,
          page: 1,
          limit: 10,
        },
        {
          id: undefined,
          messageType: undefined,
          page: 1,
          limit: 10,
        },
      ],
      ids:[],
      binding:{}
    };
  },
  onLoad(options) {
    this.top = uni.getMenuButtonBoundingClientRect().top;
    console.log(options.index !== undefined && !isNaN(options.index))
    console.log(options.index)
    if (options.index !== undefined && !isNaN(options.index)) {
      this.currentTab = parseInt(options.index);
      // this.currentTab = Math.max(0, Math.min(this.currentTab, this.tabList.length - 1));
    }
    console.log(this.currentTab)
    this.tabList = uni.getStorageSync('typeList');
    const idMap = [];
    const messageType = [];
    this.tabList.forEach(item => {
      idMap.push(item.id);
      messageType.push(item.messageType);
    });
    console.log(idMap)
    console.log(this.tabList)
    // 更新A数组的id字段
    idMap.forEach((item,index) => {
      this.$set(this.conditions[index],'id',item)
    });
    // 更新A数组的id字段
    messageType.forEach((item,index) => {
      this.$set(this.conditions[index],'messageType',item)
    });
    console.log(this.conditions)
    // this.getList()
    // 使用后清理message
    uni.removeStorageSync('typeList');
  },
  watch: {
    // 监听基本类型
    currentTab(newVal, oldVal) {
      if(this.list[newVal] && Object.keys(this.list[newVal]).length !== 0 && this.list[newVal].list){
        this.messageList = this.list[newVal].list || []
        console.log(this.list)
        console.log(this.list[newVal])
        console.log(newVal)
      }else{
        this.getList()
      }
    },
  },
  onReachBottom() {
    if (this.messageList.length > 0) {
      this.getList();
    }
  },
  methods: {
    confirmBind(bind) {
      let tit = '已拒绝'
      bindFamilyAuditApply(this.binding.applyId,bind).then(res=>{
        if(bind){
          tit = '已同意'
        }
        this.popupShow = false;
        uni.showToast({
          title: tit,
          icon: 'success',
        });
      })
    },
    close() {
      this.popupShow = false;
    },
    record(item){
      if(item.messageType = 'ACCOUNT'){
        if(item.statusStr == '待处理'){
          this.popupShow = true
          this.binding = item
        }else if(item.statusStr == '已同意'){
          uni.showToast({
            title: '您已同意',
            icon: 'none'
          });
        }else if(item.statusStr == '已拒绝'){
          uni.showToast({
            title: '您已拒绝',
            icon: 'none'
          });
        }
      }
      postMessagesRead([item.id]).then(res=>{
        if(res.code == 200){
          item.isRead = true;
        }
      })
    },
    getList(){
      console.log(this.conditions)
      getMaterialsPageList(this.conditions[this.currentTab]).then(res=>{
        this.$set(this.list[this.currentTab],'total',res.data.total)
        if (this.conditions[this.currentTab].page === 1) {
          this.list[this.currentTab].list = res.data.list || []; // 第一页直接替换
        } else {
          this.list[this.currentTab].list = [...(this.list[this.currentTab].list || []), ...(res.data.list || [])]; // 后续页追加数据
        }
        this.messageList=this.list[this.currentTab].list || []
        this.conditions[this.currentTab].page=res.data.page+1
        this.messageList.forEach((item,index) => {
          this.$set(this.ids,index,item.id)
        })
      })
    },
    back(){
      uni.navigateBack()
    },
    markAllRead() {
      console.log(this.ids)
      postMessagesRead(this.ids).then(() =>{
        // 前端同步所有消息为已读
        this.messageList.forEach(msg => {
          msg.isRead = true;
        });
        uni.showToast({
          title: '消息已经全部已读！',
          icon: 'success',
        });
      })
    },
    changeTab(e) {
      this.currentTab = e.index;
    },
    toggleExpand(index) {
      this.messageList[index].isExpand = !this.messageList[index].isExpand;
      this.$forceUpdate()
      },

    // 滑动手势处理
    onTouchStart(e) {
      this.startX = e.touches[0].clientX;
      this.lastTouchX = e.touches[0].clientX;
      this.touchStartTime = Date.now();
      this.dragOffset = 0;
      this.dragTransition = 'none';
      this.touchMoves = [];
    },

    onTouchMove(e) {
      const moveX = e.touches[0].clientX - this.startX;
      const windowWidth = uni.getSystemInfoSync().windowWidth;
      // 记录触摸移动轨迹（用于防抖）
      this.touchMoves.push(moveX);
      if (this.touchMoves.length > 5) this.touchMoves.shift();
      // 防抖判断：如果最近5次移动距离变化不大，视为抖动，直接返回
      if (this.touchMoves.length >= 5 && Math.abs(this.touchMoves[4] - this.touchMoves[0]) < 10) {
        return;
      }
      // 增加最小移动阈值，避免轻微触碰触发
      const threshold = 60;
      if (Math.abs(moveX) < threshold) return;
      // 计算拖动百分比
      let dragPercentage = (moveX / windowWidth) * 100;
      // 禁止边界拖动
      if ((this.currentTab === 0 && dragPercentage > 0) || (this.currentTab === this.tabList.length - 1 && dragPercentage < 0)) {
        dragPercentage = 0;
      }
      this.dragOffset = dragPercentage;
    },

    onTouchEnd() {
      const windowWidth = uni.getSystemInfoSync().windowWidth;
      const moveX = this.dragOffset * windowWidth / 100;
      const touchDuration = Date.now() - this.touchStartTime;
      const touchDistance = Math.abs(moveX);
      // 计算滑动速度（像素/毫秒）
      const swipeSpeed = touchDistance / touchDuration;
      // 确保动画时间一致
      const animationDuration = 300;
      this.dragTransition = `transform ${animationDuration}ms cubic-bezier(0.0, 0.0, 1.0, 1.0)`;
      // 动态阈值计算（根据滑动速度调整，速度越快阈值越低）
      const baseThreshold = windowWidth / 5;
      const speedFactor = Math.min(1, swipeSpeed * 2);
      const dynamicThreshold = baseThreshold * (1 - speedFactor * 0.5);
      // 快速滑动判断
      const isQuickSwipe = (touchDuration < 300 && touchDistance > windowWidth * 0.1) || (swipeSpeed > 0.5);
      let targetTab = this.currentTab;
      if ((moveX > dynamicThreshold && this.currentTab > 0) || (isQuickSwipe && moveX > 0 && this.currentTab > 0)) {
        targetTab--;
      } else if ((moveX < -dynamicThreshold && this.currentTab < this.tabList.length - 1) || (isQuickSwipe && moveX < 0 && this.currentTab < this.tabList.length - 1)) {
        targetTab++;
      }
      targetTab = Math.max(0, Math.min(this.tabList.length - 1, targetTab));
      if (targetTab !== this.currentTab) {
        this.currentTab = targetTab;
      }
      setTimeout(() => {
        this.dragOffset = 0;
        this.dragTransition = 'none';
      }, animationDuration);
    }
  }
};
</script>

<style lang="scss" scoped>
// 定义变量
$container-padding: 15px;
$message-padding: 10px;
$border-radius: 10px;
$transition-time: 0.3s;
$tab-height: 100rpx;
.chapter-arrow-img {
  width: 16px;
  height: 16px;
  margin-left: 6px;
  transition: transform 0.2s;
  display: inline-block;
  transform: rotate(180deg);
  &.open {
    transform: rotate(360deg);
  }
}
.container {
  height: 100vh;
  overflow: hidden;
  position: relative;
  .message-header {
    display: flex;
    align-items: center;
    margin-bottom: 30px;
    position: relative;

    .read-all {
      font-size: 14px;
      color: #8B5E3C;
      position: absolute;
      padding: 10px;
      .all{
        text-decoration: underline;
        text-decoration-color: #8B5E3C; /* 线条颜色 */
        text-decoration-thickness: 1px; /* 线条粗细 */
        text-underline-offset: 2px; /* 线条与文字的间距 */
        margin-right: 20rpx;
      }
    }
    .title {
      font-weight: bold;
      width: 100rpx;
      text-align: center;
      margin: auto;
      font-size: 1rem;
    }
  }

  .content-container {
    width: 100%;
    height: calc(100vh - #{$tab-height}); // 使用变量计算高度
    overflow: hidden;
    position: relative;

    .tab-content {
      display: flex;
      height: 100%;

      .tab-pane {
        flex-shrink: 0;
        width: 100%;
        height: 100%;
        overflow-y: auto;
        padding: 0 $container-padding;

        .message-item {
          background-color: #fff;
          padding: $message-padding;
          border-radius: $border-radius;
          margin-top: 10px;

          // 使用嵌套结构
          .msg-header {
            display: flex;
            align-items: center;
            position: relative;
            .msg-title {
              font-size: 18px;
            }

            .msg-time {
              color: #4B5563;
              position: absolute;
              right: 16px;
              font-size: 26rpx;
            }

            .message-tips {
              width: 8px;
              height: 8px;
              background-color: #EF4444;
              border-radius: 50%;
              position: absolute;
              right: 20px;
              top: 24px;
            }

            .toggle-btn {
              color: #8F4C38;
              font-size: 30rpx;
              position: absolute;
              right: 0;
            }
          }

          .msg-content-wrapper {
            font-size: 26rpx;
            overflow: hidden;
            transition: all $transition-time ease-in-out;
            .msg-text{
              color: #4B5563;
            }
          }

          .msg-content {
            max-height: 84rpx;
            opacity: 0.85;
            overflow: hidden;
            padding-top: 8px;
            padding-bottom: 0;
            transition: all 0.4s cubic-bezier(.55,0,.1,1);
          }
          .msg-content.slide-down {
            max-height: 1000px;
            opacity: 1;
            padding-bottom: 8px;
          }
        }
      }
    }
  }
}

.bind-child-popup {
  background: #fff;
  border-radius: 22px;
  padding: 48rpx 36rpx 36rpx 36rpx;
  min-width: 520rpx;
  max-width: 92vw;
  box-shadow: 0 12px 36px rgba(0,0,0,0.16);
  text-align: left;
  .popup-title {
    font-size: 38rpx;
    font-weight: 800;
    margin-bottom: 28rpx;
    color: #2d1e0f;
    text-align: center;
    letter-spacing: 1.5rpx;
  }
  .popup-content {
    font-size: 30rpx;
    color: #444;
    margin-bottom: 40rpx;
    line-height: 2.1;
    background: #faf8f6;
    border-radius: 12rpx;
    padding: 28rpx 24rpx 18rpx 24rpx;
    box-sizing: border-box;
    view {
      margin-bottom: 12rpx;
      display: flex;
      align-items: center;
      .label {
        color: #8B4513;
        font-weight: 500;
        min-width: 140rpx;
        display: inline-block;
      }
      .value {
        color: #333;
        font-weight: 400;
        margin-left: 8rpx;
        word-break: break-all;
      }
    }
  }
  .popup-actions {
    display: flex;
    gap: 32rpx;
    justify-content: center;
    margin-top: 8rpx;
    button {
      flex: 1;
      height: 88rpx;
      border-radius: 44rpx;
      font-size: 30rpx;
      border: none;
      outline: none;
      box-shadow: 0 2px 8px rgba(139,69,19,0.08);
      transition: background 0.2s, color 0.2s, box-shadow 0.2s;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0;
    }
    .btn-cancel {
      background: #f3f3f3;
      color: #b0a9a2;
      font-weight: 500;
    }
    .btn-confirm {
      background: linear-gradient(90deg, #a86b3c 0%, #8B4513 100%);
      color: #fff;
      font-weight: 600;
    }
    .btn-confirm:active {
      background: #a86b3c;
    }
    .btn-cancel:active {
      background: #e0e0e0;
    }
  }
}
</style>